// class all_businessman_to_request
// {
//     constructor(opcode)
//     {
//         this.opcode = opcode;
//     }
// }

//const { response } = require("express");

// "http://192.168.1.1:8080/server"
// "http://127.0.0.1:8080/server"
const database_server_url = "http://192.168.1.1:8080/server";

class purchase_info_to_send 
{
    constructor(opcode, userid, businessman_name, user_select_product, user_select_count) 
    {
        this.opcode = opcode;
        this.userid = userid;
        this.businessman_name = businessman_name;
        this.type_of_commodity = user_select_product;
        this.purchase_quantity = user_select_count;
    }
}

let userid = null;
let businessman_name = null;
let payment_amount = null;

// 用户选择商品的种类
let user_select_product = null;
// 用户选择商品的数量
let user_select_count = 0;
// 用户选择的这种商品的价格
let price_of_user_select_product = null;
// 用户选择的这种商品的stock
let stock_of_user_select_product = null;

// 为user_order_select_part添加一个事件监听器，以便在选项改变时能够得到user的选择
function user_order_select_part_change_event() 
{
    let user_order_select_part_element = document.getElementById("user-order-select-part");
    user_order_select_part_element.addEventListener('change', function () {
        // 获取当前选中的<option>的value值
        let selectedValue = user_order_select_part_element.value;

        // 根据选中的value执行不同的操作
        if (selectedValue === "default") 
        {
            user_select_product = "default";
            //console.log("默认选项被选中: Please enter the product you want to buy");
        }
        else {
            for (let i = 1; i < user_order_select_part_element.length; ++i) 
            {
                if (selectedValue === `product${i}`) 
                {
                    let user_select_product_id = `form-select-product${i}`;
                    let user_select_option_element = document.getElementById(user_select_product_id);
                    user_select_product = user_select_option_element.innerText;
                    price_of_user_select_product = user_select_option_element.getAttribute("data-price");
                    stock_of_user_select_product = user_select_option_element.getAttribute("data-stock");
                    stock_of_user_select_product = parseInt(stock_of_user_select_product, 10);
                    break;
                }
            }
        }

    });
}

// 提交用户订单事件的绑定
function submit_user_order_event() 
{
    const submit_user_order_btn = document.getElementById("submit-user-order-button");
    submit_user_order_btn.addEventListener("click", function () {
        // 首先需要读取表单数据, 进行初步判断
        // 确定购买的数量
        let user_order_count_part_element = document.getElementById("user-order-count-part");
        user_select_count = parseInt(user_order_count_part_element.value, 10);
        //payment_amount = user_select_count * price_of_user_select_product;
        //console.log(user_select_count, typeof user_select_count);
        //console.log(stock_of_user_select_product, typeof stock_of_user_select_product);
        //console.log(price_of_user_select_product, typeof price_of_user_select_product);
        // 判断user选择了哪一种商品, 购买的数量, 是否合法
        if (user_select_count > 0 && user_select_product !== "default" && user_select_count <= stock_of_user_select_product) 
        {
            // 给服务端发送信息
            //console.log("给服务端发送信息");
            //const xhr = new XMLHttpReqeust(); quest
            const xhr = new XMLHttpRequest();
            xhr.open("POST", database_server_url);
            xhr.setRequestHeader("Content-Type", "application/json");

            xhr.onreadystatechange = function () 
            {
                if (xhr.readyState === 4) 
                {
                    // 解析响应体
                    let response_body = JSON.parse(xhr.responseText);
                    //console.log(response_body);
                    //console.log(xhr.responseText);
                    if (xhr.status >= 200 && xhr.status < 300) 
                    {
                        // 成功收到响应体
                        if (response_body.rc === "success") 
                        {
                            // 提醒用户已完成购买
                            console.log("已完成购买");
                            // 跳转回Home
                            let nav_link_home_element = document.getElementById("nav-link-home");
                            nav_link_home_element.click();
                        }
                    }
                }
                else 
                {
                    ;
                }
            }

            //let data_to_send = `{"opcode":6, "userid":${userid}, "businessman_name":${businessman_name}, "type_of_commodity":${user_select_product}, "purchase_quantity":${user_select_count}}`;
            let data_to_send = new purchase_info_to_send(6, userid, businessman_name, user_select_product, user_select_count);
            //console.log(data_to_send);
            //console.log(userid);
            //console.log(data_to_send);
            let message_to_send = JSON.stringify(data_to_send);
            console.log(data_to_send);
            console.log(message_to_send);
            xhr.send(message_to_send);
        }
        else 
        {
            console.log("user_select_product or user_order_count is invalid");
        }

    });



}

// 渲染商品界面
function render_shopping_pane_commodity(businessman_name) 
{
    //console.log(2);
    const xhr = new XMLHttpRequest();
    xhr.open("POST", database_server_url);
    xhr.setRequestHeader("Content-Type", "application/json");
    xhr.onreadystatechange = function () 
    {
        if (xhr.readyState === 4) 
        {
            //console.log(2);
            if (xhr.status >= 200 && xhr.status < 300) 
            {
                //console.log(1);
                let response_body = JSON.parse(xhr.responseText);
                //console.log(xhr.responseText);
                //console.log(response_body);
                let parser = new DOMParser();
                const commodity_list_parent_element = document.getElementsByClassName("commdity-list")[0];
                let user_order_select_part_element = document.getElementById("user-order-select-part");
                if (response_body && Array.isArray(response_body)) 
                {
                    for (let i = 0; i < response_body.length; ++i) 
                    {
                        let commodity = response_body[i];
                        let commodityRowHtml = `<div class="row a-commodity">
                                                <div class="col-md-4 border bg-light text-center specific-type"><p class="mb-0 p-3">${commodity.type}</p></div>
                                                <div class="col-md-4 border bg-light text-center specific-stock"><p class="mb-0 p-3">${commodity.amount}</p></div>
                                                <div class="col-md-4 border bg-light text-center specific-price"><p class="mb-0 p-3">${commodity.price}</p></div>
                                                </div>`;
                        let a_commodity_row_document = parser.parseFromString(commodityRowHtml, 'text/html');
                        let commodityRowElement = a_commodity_row_document.body.firstChild; // 获取 <div class="row a-commodity fade">
                        //console.log(commodityRowElement, typeof commodityRowElement);
                        commodity_list_parent_element.appendChild(commodityRowElement);

                        // 还需要为表单下拉选择框添加选项
                        let option_element = document.createElement("option");
                        option_element.setAttribute("value", `product${i + 1}`);
                        option_element.setAttribute("id", `form-select-product${i + 1}`);
                        option_element.setAttribute("data-price", commodity.price);
                        option_element.setAttribute("data-stock", commodity.amount);
                        option_element.innerText = commodity.type;
                        user_order_select_part_element.appendChild(option_element);

                    }

                    // 显示commodify-hr
                    let commdity_hr = document.getElementsByClassName("commdity-hr")[0];
                    commdity_hr.classList.remove("fade");
                    // 渲染表单
                    let user_order = document.getElementById("user-order");
                    user_order.setAttribute("style", "");
                }
            }
            else 
            {
                console.log("");
            }
        }
    };

    xhr.send(`{"opcode":4, "businessman_name": "${businessman_name}"}`);
}

// come_in button绑定事件
function click_event_of_come_in_btn() 
{
    const come_in_btns = document.getElementsByClassName("come_in");
    //console.log(come_in_btns);
    for (let i = 0; i < come_in_btns.length; ++i) 
    {
        let come_in_btn = come_in_btns[i];
        // 绑定事件
        come_in_btn.addEventListener("click", function () 
        {
            // 清空shopping页面的当前内容, 即classname=shopping-tab-pane-content-businessman标签中的内容
            let tab_pane_content_businessman_element = document.getElementsByClassName("shopping-tab-pane-content-businessman")[0];
            if (!tab_pane_content_businessman_element) 
            {
                console.log('click_event_of_come_in_btn: fail to getElementsByClassName("shopping-tab-pane-content-businessman")[0]');
            }
            tab_pane_content_businessman_element.innerText = "";
            let shopping_goods_header_element = document.getElementsByClassName("shopping-goods-header")[0];
            shopping_goods_header_element.classList.remove("fade");
            //console.log(come_in_btn.businessman_name);
            // 渲染商品界面
            render_shopping_pane_commodity(come_in_btn.getAttribute("data-businessman_name"));
            console.log("data-businessman_name: ", come_in_btn.getAttribute("data-businessman_name"));
            businessman_name = come_in_btn.getAttribute("data-businessman_name");
        });
    }

}

// 渲染商人界面
function render_stopping_pane_businessman() 
{
    // 请求
    const xhr = new XMLHttpRequest();
    xhr.open("POST", database_server_url);
    xhr.setRequestHeader("Content-Type", "application/json");

    xhr.onreadystatechange = function () 
    {
        if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) 
            {
                let response_body = JSON.parse(xhr.responseText);
                //console.log(response_body);
                //console.log(xhr.responseText);
                const parent_shopping_element = document.getElementsByClassName("shopping-tab-pane-content-businessman")[0];
                //console.log(parent_shopping_element);
                if (response_body && Array.isArray(response_body)) 
                {
                    for (let i = 0; i < response_body.length; ++i) 
                    {
                        let row_element_1 = document.createElement("div");
                        row_element_1.setAttribute("class", "row tab-pane-content");
                        let col_element_1 = document.createElement("h4");
                        col_element_1.setAttribute("class", "col-md-12 mb-0");
                        col_element_1.innerText = response_body[i].name;
                        row_element_1.appendChild(col_element_1);
                        parent_shopping_element.appendChild(row_element_1);

                        let row_element_2 = document.createElement("div");
                        row_element_2.setAttribute("class", "row tab-pane-content");
                        let col_element_2 = document.createElement("a");
                        col_element_2.setAttribute("class", "btn btn-block btn-light col-md-2 offset-md-10 text-center come_in");
                        col_element_2.setAttribute("href", "#");
                        col_element_2.setAttribute("data-businessman_name", response_body[i].name);
                        //console.log(col_element_2.getAttribute("businessman_name"));
                        //console.log(response_body.table[i].name);
                        col_element_2.innerText = "Come in";
                        row_element_2.appendChild(col_element_2);
                        parent_shopping_element.appendChild(row_element_2);
                    }

                    // 为所有的classname="come_in"的按钮添加click事件
                    click_event_of_come_in_btn();
                }
                else 
                {
                    console.log("render_stopping_pane: fail to parse JSON");
                }

            }
        }
    }

    xhr.send('{"opcode":3}');
}

// 重置表单
function reset_user_order() {
    // 删除user-order-select-part它的非默认选项
    let user_order_select_part_element = document.getElementById("user-order-select-part");

    // 检查是否成功获取到元素
    if (user_order_select_part_element) {
        // 遍历<select>元素内的所有<option>子元素
        for (let i = user_order_select_part_element.options.length - 1; i > 0; i--) {
            // 从最后一个选项开始向前遍历，并移除非默认选项
            // 假定默认选项是第一个<option>元素
            user_order_select_part_element.remove(i);
        }
    }
    else {
        console.error("未找到类名为'user-order-select-part'的<select>元素");
    }

    // 重置user-order-count-part的值为0
    let user_order_count_part_element = document.getElementById("user-order-count-part");
    user_order_count_part_element.value = 0;
}

// 相当于主函数
// 选项卡 
document.addEventListener('DOMContentLoaded', function () {
    // 获取当前页面的URL
    let url = window.location.href;
    // 使用URLSearchParams对象解析查询字符串
    let params = new URLSearchParams(url.split('?')[1]);
    // 获取userId参数的值
    userid = params.get("userid");
    // 现在你可以使用userId变量了，例如显示在页面上或发送到服务器
    //console.log("User ID:", userid);

    // 获取所有的选项卡链接
    let tabs = document.querySelectorAll('.nav-tabs .nav-link'); // 选择所有属于类名为 nav-tabs 的元素的后代中，所有类名为 nav-link 的元素
    // 获取所有的选项卡内容区域
    let panes = document.querySelectorAll('.tab-content .tab-pane');

    // 移除所有 tab pane 的初始内容（如果有的话）
    panes.forEach(function (pane) {
        // 假设每个 .tab-pane 里有一个 .tab-pane-content 来存放内容
        let content = pane.querySelector('.tab-pane-content');
        if (content) 
        {
            content.innerHTML = ''; // 清空内容
        }
        else 
        {
            // 如果没有 .tab-pane-content，则创建一个
            let newContent = document.createElement('div');
            newContent.className = 'tab-pane-content';
            pane.appendChild(newContent);
        }
    });

    // 为user_order_select_part添加一个事件监听器，以便在选项改变时能够得到user的选择
    user_order_select_part_change_event();
    // 提交用户订单事件的绑定
    submit_user_order_event();

    // 为每个选项卡链接添加点击事件监听器
    for (let i = 0; i < tabs.length; ++i) 
    {
        let tab = tabs[i];
        tab.addEventListener('click', function (event) 
        {
            //console.log(event);

            // 阻止默认的锚点跳转行为
            event.preventDefault(); // 不要执行与该事件关联的默认行为

            // 移除所有选项卡链接和内容区域的 active 和 show 类    
            tabs.forEach(function (t) {
                t.classList.remove('active');
            });
            panes.forEach(function (p) {
                p.classList.remove('active', 'show');
            });

            // 添加 active 类到当前点击的选项卡链接
            tab.classList.add('active');

            // 获取与当前选项卡链接相关联的内容区域的 ID（从 href 属性中提取）
            let targetId = tab.getAttribute('href').substring(1); // 去掉前面的 '#'

            // 添加 active 和 show 类到对应的内容区域
            let targetPane = document.getElementById(targetId);

            if (targetId === "shopping") 
            {
                // 在渲染之前先要清空
                // 移除shopping-tab-pane-content-businessman区域的所有内容
                let tab_pane_content_businessman_element = document.getElementsByClassName("shopping-tab-pane-content-businessman")[0];
                tab_pane_content_businessman_element.innerText = "";
                // 隐藏shopping-goods-header
                let shopping_goods_header_element = document.getElementsByClassName("shopping-goods-header")[0];
                // 移除shopping-tab-pane-content-businessman区域的所有内容
                let commdity_list_element = document.getElementsByClassName("commdity-list")[0];
                commdity_list_element.innerText = "";
                // 隐藏commdity-hr
                let commdity_hr = document.getElementsByClassName("commdity-hr")[0];
                commdity_hr.classList.add("fade");
                // 隐藏 user-order 表单 none型隐藏
                let user_order = document.getElementById("user-order");
                user_order.setAttribute("style", "display: none;");
                // // 为user-order 添加绑定事件, 使其在隐藏时, 不能触发点击
                // user_order('click')
                // 重置表单
                reset_user_order();

                //console.log(shopping_goods_header_element);
                shopping_goods_header_element.classList.add("fade");
                // 渲染商人界面->以及后续的shopping界面
                render_stopping_pane_businessman();
            }

            targetPane.classList.add('active', 'show');

        });

    }

});